import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:hzcloud_flt/feature/router.dart';
import 'package:hzcloud_flt/feature/views/home.menus.view.dart';
import 'package:hzcloud_flt/feature/views/home_banner.view.dart';
import 'package:hzcloud_flt/feature/views/index.list.view.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'
    as extended;
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController _tabController;
  Key tabKey;
  final List<String> _tabValues = [
    '语文',
    '英语',
    '化学',
    '物理物理物理',
    '物理',
    '物理物理物理物理',
    '物理',
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: _tabValues.length,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Widget buildPulltoRefreshHeader(PullToRefreshScrollNotificationInfo info) {
    var offset = info?.dragOffset ?? 0.0;
    var mode = info?.mode;
    Widget refreshWidget = Container();
    if (info?.refreshWidget != null &&
        offset > 18.0 &&
        mode != RefreshIndicatorMode.error) {
      refreshWidget = Image.asset(
        'assets/images/loading_dynamic_icon.gif',
        width: 20,
      );
    }

    Widget child;
    if (mode == RefreshIndicatorMode.error) {
      child = GestureDetector(
          onTap: () {
            // refreshNotification;
            info?.pullToRefreshNotificationState?.show();
          },
          child: Container(
            color: Colors.grey,
            alignment: Alignment.bottomCenter,
            height: offset,
            width: double.infinity,
            //padding: EdgeInsets.only(top: offset),
            child: Container(
              padding: EdgeInsets.only(left: 5.0),
              alignment: Alignment.center,
              child: Text(
                mode?.toString() + "  click to retry" ?? "",
                style: TextStyle(fontSize: 12.0, inherit: false),
              ),
            ),
          ));
    } else {
      String tip = "";
      switch (mode) {
        case RefreshIndicatorMode.armed:
          {
            tip = "松开刷新";
          }
          break;
        case RefreshIndicatorMode.canceled:
          {
            tip = "取消刷新";
          }
          break;
        case RefreshIndicatorMode.refresh:
          {
            tip = "加载中...";
          }
          break;
        case RefreshIndicatorMode.drag:
          {
            tip = "下拉刷新...";
          }
          break;
        default:
          {
            tip = "";
          }
      }
      child = Container(
        color: Colors.white,
        alignment: Alignment.center,
        height: offset,
        width: double.infinity,
        //padding: EdgeInsets.only(top: offset),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            refreshWidget,
            Container(
              padding: EdgeInsets.only(left: 5.0),
              alignment: Alignment.center,
              child: Text(
                tip,
                style: TextStyle(
                    fontSize: 15.0, color: Color(0xFF333333), inherit: false),
              ),
            )
          ],
        ),
      );
    }
    return SliverToBoxAdapter(
      child: child,
    );
  }

  buildTabNewsList() {}

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(
          children: [
            Expanded(
              child: GestureDetector(
                onTap: () {
                  BoostNavigator.instance
                      .push(HZRouter.instance.pageModule.switchParkPage.path);
                },
                child: Row(
                  children: [
                    Flexible(
                        child: Text(
                      '金马二区',
                      style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF333333)),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )),
                    Padding(
                      padding: EdgeInsets.only(left: 5),
                      child: Image.asset(
                          'assets/images/arrow_down_solid_gray.png'),
                    )
                  ],
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                BoostNavigator.instance
                    .push(HZRouter.instance.nativeModule.qrscan.path);
              },
              child: CircleAvatar(
                backgroundColor: Color(0xFFF2F2F2),
                child: Image.asset('assets/images/scan.png'),
              ),
            )
          ],
        ),
        elevation: 0.5,
      ),
      body: PullToRefreshNotification(
        pullBackOnRefresh: true,
        onRefresh: () {},
        maxDragOffset: 70,
        child: extended.NestedScrollView(
          pinnedHeaderSliverHeightBuilder: () {
            return 50;
          },
          innerScrollPositionKeyBuilder: () {
            int index = _tabController.index;
            Key key = Key(_tabValues[index]);
            return key;
          },
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              PullToRefreshContainer(buildPulltoRefreshHeader),
              SliverToBoxAdapter(
                child: HomeBannerView(),
              ),
              SliverPadding(
                padding: EdgeInsets.only(left: 15, right: 15, bottom: 10),
                sliver: HomeMenusView(),
              ),
              SliverToBoxAdapter(
                child: Container(
                  height: 10,
                  color: Color(0xFFF2F2F2),
                ),
              ),
              SliverToBoxAdapter(
                child: TabBar(
                  controller: _tabController,
                  indicatorSize: TabBarIndicatorSize.label,
                  indicatorWeight: 3,
                  labelColor: Colors.blueAccent,
                  labelStyle: TextStyle(fontSize: 15),
                  unselectedLabelColor: Colors.grey,
                  unselectedLabelStyle: TextStyle(fontSize: 15),
                  tabs:
                      _tabValues.map((String name) => Tab(text: name)).toList(),
                  isScrollable: true,
                ),
              ),
            ];
          },
          body: TabBarView(
            controller: this._tabController,
            children: _tabValues.map(
              (e) {
                return extended.NestedScrollViewInnerScrollPositionKeyWidget(
                  Key(e),
                  IndexListView(),
                );
              },
            ).toList(),
          ),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar tab;

  // final Widget topView;

  StickyTabBarDelegate({@required this.tab});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Theme.of(context).backgroundColor,
      child: tab,
    );
  }

  @override
  double get maxExtent => this.tab.preferredSize.height;

  @override
  double get minExtent => this.tab.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
